package com.ychen.nttey;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * @author chenyuliao
 * @version 1.0
 * @description
 * @date 2021/1/4 20:34
 */
public class DiscardServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 默默地丢弃收到的数据
//        ((ByteBuf) msg).release(); // (3)
//        ByteBuf in = (ByteBuf) msg;
//        try {
//            System.out.println(in.toString(io.netty.util.CharsetUtil.US_ASCII));
////            while (in.isReadable()) { // (1)
////                System.out.print((char) in.readByte());
////                System.out.flush();
////            }
//
//        } finally {
//            ReferenceCountUtil.release(msg); // (2)
//        }
        ctx.write(msg); // (1)
        ctx.flush(); // (2)
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}
